# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(tidyverse)
library(magrittr)
library(tools)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

isCorExec <- configData["cor.isCorExec", "value"] == "T"
print(isCorExec)

parent <- paste0("./")
createWhenNoExist(parent)

workspacePath <- "../../"

dir <- str_c(workspacePath)
dirs <- list.dirs(dir, recursive = F) %>%
  keep(~str_detect(.x, "_vs_")) %>%
  keep(function(dirName) {
    length <- basename(dirName) %>%
      str_split("_vs_") %>%
      unlist() %>%
      length()
    length == 2
  })
treats <- basename(dirs)

if (length(treats) == 0) {
  quit(status = 0)
}

uploadDirs <- str_c(workspacePath, "/cor_extra_data") %>%
  list.files(full.names = T) %>%
  basename() %>%
  file_path_sans_ext()
uploadDirs

if (!isCorExec) {
  quit(status = 0)
}

for (uploadDir in uploadDirs) {
  createWhenNoExist(uploadDir)
  tbf <- tibble()
  for (treat in treats) {
    subDir <- str_c(workspacePath, treat, "/cor/01")
    fileParent <- list.dirs(subDir, recursive = F) %>%
      keep(~str_detect(.x, "_and_")) %>%
      head(1)
    filePath <- str_c(fileParent, "/", uploadDir, "/Network_Nodes_for_Cytoscape.csv")

    if (!file.exists(filePath)) {
      treats <- treats %>%
        discard(~.x == treat)
      next
    }

    data <- read_csv(filePath) %>%
      select("Node") %>%
      rename_at(vars(c("Node")), function(x) {
        c(treat)
      })
    if (nrow(data) > 0) {
      data <- data %>%
        mutate(id = 1:n())
    }else {
      data <- data %>%
        add_column(id = NA)
    }
    if (ncol(tbf) == 0) {
      tbf <- data
    }else {
      tbf <- tbf %>%
        full_join(data, by = "id")
    }
  }

  columnNames <- treats
  outData <- tbf
  size <- length(columnNames)

  if (length(columnNames) > 1 & length(columnNames) < 5) {
    for (i in size:2) {
      cn <- combn(columnNames, i)
      for (i in 1:ncol(cn)) {
        row <- cn[, i]
        columnName <- str_c(row, collapse = " & ")
        outData <- outData %>%
          mutate(!!columnName := {
            values <- row %>%
              map(function(t) {
                get(t)
              })
            x <- Reduce(intersect, values)
            x[1:n()]
          })
      }
    }
  }else {
    for (i in size:size) {
      cn <- combn(columnNames, i)
      for (i in 1:ncol(cn)) {
        row <- cn[, i]
        columnName <- str_c(row, collapse = " & ")
        outData <- outData %>%
          mutate(!!columnName := {
            values <- row %>%
              map(function(t) {
                get(t)
              })
            x <- Reduce(intersect, values)
            x[1:n()]
          })
      }
    }
  }

  if (length(columnNames) < 5) {
    for (name in columnNames) {
      newName <- str_c(name, " only")
      outData <- outData %>%
        mutate(!!newName := {
          otherNames <- columnNames %>%
            discard(~.x %in% c(name))
          values <- c(name, otherNames) %>%
            map(function(t) {
              get(t)
            })
          x <- Reduce(setdiff, values)
          x[1:n()]
        })
    }
  }

  outData <- outData %>%
    mutate_all(function(x) {
      replace_na(x, "")
    })
  if (length(columnNames) >= 5) {
    outData <- outData %>%
      select((size + 2), columnNames)
  }else {
    outData <- outData %>%
      select(-c(1:(size + 1)))
  }
  outData
  outFileName <- str_c(uploadDir, "/Inter_Correlation_Venn_Data_By_TwoGroup_Compares.csv")
  write_csv(outData, outFileName)
}







